#!/bin/sh

set -x
set +e
mkdir /root/result/{build/{srpms,rpms},chroot_logs/PKGS} -p

log_dir="/root/result/chroot_logs/PKGS"
builddep_log="/root/result/chroot_logs/builddep_log"

srclist=$1
srcpkg=$2
baserpmbuild=$3
mkdir -p $baserpmbuild

output_dir_srpm="/root/result/build/srpms"
output_dir_rpm="/root/result/build/rpms"

for pkg in $(cat $srclist);
do
    pkg=$srcpkg/$pkg
    rpmname=$(basename $pkg)
    yum-builddep -y --allowerasing $pkg  > "$log_dir"/"$rpmname".log 2>&1
    if [ $? -ne 0 ]; then
        echo "Failed to build dependencies for "$log_dir"/"$rpmname".log" >> "$builddep_log"
    else
         timeout_status=0
         # 使用timeout设置超时限制为3小时,超时的包后单独处理不再浪费时间
         timeout 3h rpmbuild -ra --define "_topdir $baserpmbuild" --nocheck $pkg >> "$log_dir"/"$rpmname".log 2>&1
         timeout_status=$?
         if [ $timeout_status -eq 124 ]; then
           echo "Timeout: $srcRpmFile compilation exceeded 3h" >> "$log_dir"/"$rpmname".log
         elif [ $timeout_status -ne 0 ]; then
           echo "Failed to build package $srcRpmFile" >> "$log_dir"/"$rpmname".log
         else 
           mv $baserpmbuild/SRPMS/* $output_dir_srpm/
           mv $baserpmbuild/RPMS/*/* $output_dir_rpm/
         fi
    fi
    rm -rf $baserpmbuild/*           
done
